<?php


namespace app\api\controller\v2;


use api\channel\jutuike\MeituanJutuikeSeckillUnion;
use api\channel\meituan\alliance\Seckill;
use app\common\service\MeituanPub;
use app\common\service\MeituanPubJutuike;
use app\middleware\MeituanCityNameToCityId;
use think\Request;

/**
 * Class MeituanSeckill
 * @package app\api\controller\v2
 */
class Meituan extends \app\BaseController
{
    protected $middleware = [
        \app\middleware\ApiChannel::class,
        \app\middleware\ApiUserAuthV2::class,
        MeituanCityNameToCityId::class,
    ];

    protected function initialize()
    {
        $this->request->servType = PRODUCT_SECKILL_SERV;
        $this->request->servName = '渠道';

        //验证是美团的还是聚推客的
        parent::initialize();
    }

    //有聚推客渠道的秒杀，可查看git版本历史查看 2022年5月18日10:13:50

    /**
     * 秒杀时间
     */
    public function seckillShowInfo(Request $request){

        $params = request()->all();

        $params['cityId'] = $request->cityId;

        $service = $this->getService($params);

        $res = $service->seckillShowInfo();

        if (!in_array($res['code'],[1,200])){
            return fail($res['msg']);
        }

        if ($service instanceof MeituanJutuikeSeckillUnion){
            $data['list'] = $res['data'];
        }else{
            $data['list'] = $res['msg'];
        }




        $data['current_time'] = bcmul(microtime(true), 1000);

        return  success('',$data);
    }

    public function seckillList(Request $request){

        $params = request()->all();


        if (empty($params['cityId']))$params['cityId'] = $request->cityId;

        $showId = $params['showId']??'';
        $meituanPub = $this->getService();
        if (!$showId){
            //获取默认的场次
            $res = $meituanPub->seckillShowInfo();

            if ($res['code'] != 200){
                return fail($res['msg']);
            }
            if (empty($res['msg'][0])){
                return fail('当前无场次');
            }
            $time = $res['msg'][0];

            $params['showId'] = $time['showId'];

        }

        $params['agent_id'] = $this->request->agentChannel['agent_id'];
        $params['user_id'] = $this->request->user['id'];
        $params['channel_id'] = $this->request->agentChannel['id'];

        $meituanPub = $this->getService($params);


        $res = $meituanPub->seckillList($params);

        if (!empty($res['code']) && $res['code'] != 200){
            return fail($res['msg']);
        }

        if (isset($time)){
            $res['msg']['timeInfo'] = $time;
        }

        return  success('',$res['msg']);
    }

    /**
     * initialize 方法在中间件之前执行，如果放在初始化中则会报错
     */
    protected function getService($params =[]){
        if (env('MEITUAN_IS_JUTUIKE')){
            return new MeituanJutuikeSeckillUnion();
        }else{
            return new Seckill($params);
        }

    }

}